/**
 * 自动检查和修复题库
 * 
 * 功能：
 * 1. 自动检查所有题目
 * 2. 验证数学计算
 * 3. 自动修复简单错误
 * 4. 生成详细报告
 */

const fs = require('fs');
const path = require('path');

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
};

function log(color, ...args) {
  console.log(color, ...args, colors.reset);
}

// 验证结果
const results = {
  total: 0,
  checked: 0,
  passed: 0,
  warnings: 0,
  errors: 0,
  autoFixed: 0,
  issues: [],
};

// 数学验证器
class MathVerifier {
  // 鸡兔同笼验证
  static verifyChickenRabbit(stem, answer) {
    const match = stem.match(/共有头(\d+)个.*脚(\d+)只/);
    if (!match) return null;
    
    const heads = parseInt(match[1]);
    const feet = parseInt(match[2]);
    const givenAnswer = parseInt(answer[0]);
    
    // 计算正确答案
    const chickens = (4 * heads - feet) / 2;
    const rabbits = heads - chickens;
    
    // 检查是否为整数
    if (chickens % 1 !== 0 || rabbits % 1 !== 0) {
      return {
        valid: false,
        error: `数据不合理：头${heads}个，脚${feet}只，无法得到整数解`,
        canFix: false,
      };
    }
    
    // 检查是否为正数
    if (chickens < 0 || rabbits < 0) {
      return {
        valid: false,
        error: `数据不合理：头${heads}个，脚${feet}只，得到负数`,
        canFix: false,
      };
    }
    
    // 判断题目问的是鸡还是兔
    const askingChicken = stem.includes('鸡有') || stem.includes('鸡多少');
    const correctAnswer = askingChicken ? chickens : rabbits;
    
    if (givenAnswer !== correctAnswer) {
      return {
        valid: false,
        error: `答案错误：应该是${correctAnswer}，但给出的是${givenAnswer}`,
        canFix: true,
        correctAnswer: correctAnswer,
        correctSolution: `设鸡有x只，兔有(${heads}-x)只。\n根据脚的数量：2x + 4(${heads}-x) = ${feet}\n解得：x = ${chickens}\n所以鸡有${chickens}只，兔有${rabbits}只。`,
      };
    }
    
    return { valid: true };
  }
  
  // 简单加减法验证
  static verifyAddition(stem, answer) {
    const match = stem.match(/(\d+)\s*\+\s*(\d+)/);
    if (!match) return null;
    
    const a = parseInt(match[1]);
    const b = parseInt(match[2]);
    const givenAnswer = parseInt(answer[0]);
    const correctAnswer = a + b;
    
    if (givenAnswer !== correctAnswer) {
      return {
        valid: false,
        error: `加法错误：${a} + ${b} = ${correctAnswer}，但给出的是${givenAnswer}`,
        canFix: true,
        correctAnswer: correctAnswer,
      };
    }
    
    return { valid: true };
  }
  
  // 简单乘法验证
  static verifyMultiplication(stem, answer) {
    const match = stem.match(/(\d+)\s*[×x]\s*(\d+)/);
    if (!match) return null;
    
    const a = parseInt(match[1]);
    const b = parseInt(match[2]);
    const givenAnswer = parseInt(answer[0]);
    const correctAnswer = a * b;
    
    if (givenAnswer !== correctAnswer) {
      return {
        valid: false,
        error: `乘法错误：${a} × ${b} = ${correctAnswer}，但给出的是${givenAnswer}`,
        canFix: true,
        correctAnswer: correctAnswer,
      };
    }
    
    return { valid: true };
  }
  
  // 长方形面积验证
  static verifyRectangleArea(stem, answer) {
    const match = stem.match(/长.*?(\d+(?:\.\d+)?)\s*(?:厘米|米|cm|m).*?宽.*?(\d+(?:\.\d+)?)\s*(?:厘米|米|cm|m)/);
    if (!match || !stem.includes('面积')) return null;
    
    const length = parseFloat(match[1]);
    const width = parseFloat(match[2]);
    const givenAnswer = parseFloat(answer[0]);
    const correctAnswer = length * width;
    
    if (Math.abs(givenAnswer - correctAnswer) > 0.01) {
      return {
        valid: false,
        error: `长方形面积错误：${length} × ${width} = ${correctAnswer}，但给出的是${givenAnswer}`,
        canFix: true,
        correctAnswer: correctAnswer,
      };
    }
    
    return { valid: true };
  }
  
  // 长方形周长验证
  static verifyRectanglePerimeter(stem, answer) {
    const match = stem.match(/长.*?(\d+(?:\.\d+)?)\s*(?:厘米|米|cm|m).*?宽.*?(\d+(?:\.\d+)?)\s*(?:厘米|米|cm|m)/);
    if (!match || !stem.includes('周长')) return null;
    
    const length = parseFloat(match[1]);
    const width = parseFloat(match[2]);
    const givenAnswer = parseFloat(answer[0]);
    const correctAnswer = 2 * (length + width);
    
    if (Math.abs(givenAnswer - correctAnswer) > 0.01) {
      return {
        valid: false,
        error: `长方形周长错误：2 × (${length} + ${width}) = ${correctAnswer}，但给出的是${givenAnswer}`,
        canFix: true,
        correctAnswer: correctAnswer,
      };
    }
    
    return { valid: true };
  }
}

// 检查题目完整性
function checkIntegrity(question, topicName, index) {
  const issues = [];
  
  if (!question.stem || question.stem.trim() === '') {
    issues.push({ type: 'error', message: '题干为空' });
  }
  
  if (!question.answer || question.answer.length === 0) {
    issues.push({ type: 'error', message: '答案为空' });
  }
  
  if (!question.solution || question.solution.trim() === '') {
    issues.push({ type: 'warning', message: '解析为空' });
  }
  
  if (!question.difficulty || question.difficulty < 1 || question.difficulty > 5) {
    issues.push({ type: 'warning', message: '难度值无效' });
  }
  
  if (question.stem && question.stem.length < 10) {
    issues.push({ type: 'warning', message: '题干过短' });
  }
  
  if (question.solution && question.solution.length < 15) {
    issues.push({ type: 'warning', message: '解析过短' });
  }
  
  return issues;
}

// 验证题目
function verifyQuestion(question, topicName, topicId, index) {
  results.total++;
  results.checked++;
  
  // 检查完整性
  const integrityIssues = checkIntegrity(question, topicName, index);
  
  // 数学验证
  let mathResult = null;
  
  // 根据题型选择验证器
  if (topicId.includes('鸡兔同笼')) {
    mathResult = MathVerifier.verifyChickenRabbit(question.stem, question.answer);
  } else if (question.stem.includes('面积') && question.stem.includes('长') && question.stem.includes('宽')) {
    mathResult = MathVerifier.verifyRectangleArea(question.stem, question.answer);
  } else if (question.stem.includes('周长') && question.stem.includes('长') && question.stem.includes('宽')) {
    mathResult = MathVerifier.verifyRectanglePerimeter(question.stem, question.answer);
  } else if (question.stem.match(/^\d+\s*\+\s*\d+/)) {
    mathResult = MathVerifier.verifyAddition(question.stem, question.answer);
  } else if (question.stem.match(/^\d+\s*[×x]\s*\d+/)) {
    mathResult = MathVerifier.verifyMultiplication(question.stem, question.answer);
  }
  
  // 记录结果
  if (mathResult && !mathResult.valid) {
    results.errors++;
    results.issues.push({
      topic: topicName,
      topicId: topicId,
      index: index + 1,
      type: 'error',
      message: mathResult.error,
      canFix: mathResult.canFix,
      correctAnswer: mathResult.correctAnswer,
      correctSolution: mathResult.correctSolution,
      question: question.stem.substring(0, 60) + '...',
    });
  } else if (integrityIssues.length > 0) {
    const hasError = integrityIssues.some(i => i.type === 'error');
    if (hasError) {
      results.errors++;
    } else {
      results.warnings++;
    }
    results.issues.push({
      topic: topicName,
      topicId: topicId,
      index: index + 1,
      type: hasError ? 'error' : 'warning',
      message: integrityIssues.map(i => i.message).join(', '),
      canFix: false,
      question: question.stem.substring(0, 60) + '...',
    });
  } else {
    results.passed++;
  }
}

// 读取题库文件
function loadQuestions(filePath) {
  try {
    const content = fs.readFileSync(filePath, 'utf-8');
    const match = content.match(/export const questions.*?=\s*(\[[\s\S]*?\]);/);
    if (!match) return null;
    
    // 使用eval解析（仅用于本地脚本）
    return eval(match[1]);
  } catch (error) {
    log(colors.red, `  ❌ 读取失败: ${error.message}`);
    return null;
  }
}

// 主函数
async function main() {
  console.log('\n' + '='.repeat(60));
  log(colors.cyan, '🔍 自动检查题库');
  console.log('='.repeat(60) + '\n');
  
  const questionsDir = path.join(__dirname, '../../questions');
  const dirs = [
    { path: path.join(questionsDir, 'primary-school'), name: '小学' },
    { path: path.join(questionsDir, 'middle-school'), name: '初中' },
  ];
  
  for (const dir of dirs) {
    log(colors.blue, `\n📚 检查${dir.name}题目...`);
    
    const files = fs.readdirSync(dir.path).filter(f => f.endsWith('.ts'));
    
    for (const file of files) {
      const topicName = file.replace('.ts', '');
      const topicId = topicName;
      process.stdout.write(`  检查: ${topicName} ... `);
      
      const questions = loadQuestions(path.join(dir.path, file));
      if (!questions) {
        log(colors.red, '失败');
        continue;
      }
      
      questions.forEach((q, i) => verifyQuestion(q, topicName, topicId, i));
      log(colors.green, `✓ (${questions.length}题)`);
    }
  }
  
  // 生成报告
  console.log('\n' + '='.repeat(60));
  log(colors.cyan, '📊 检查报告');
  console.log('='.repeat(60));
  console.log(`总题目数: ${results.total}`);
  log(colors.green, `✅ 通过: ${results.passed} (${(results.passed/results.total*100).toFixed(1)}%)`);
  log(colors.red, `❌ 错误: ${results.errors} (${(results.errors/results.total*100).toFixed(1)}%)`);
  log(colors.yellow, `⚠️  警告: ${results.warnings} (${(results.warnings/results.total*100).toFixed(1)}%)`);
  console.log('='.repeat(60));
  
  // 显示错误
  const errors = results.issues.filter(i => i.type === 'error');
  if (errors.length > 0) {
    log(colors.red, `\n❌ 发现 ${errors.length} 个错误：\n`);
    errors.forEach((err, i) => {
      console.log(`${i + 1}. ${err.topic} - 第${err.index}题`);
      console.log(`   题目: ${err.question}`);
      log(colors.red, `   错误: ${err.message}`);
      if (err.canFix && err.correctAnswer !== undefined) {
        log(colors.green, `   正确答案: ${err.correctAnswer}`);
      }
      console.log('');
    });
  }
  
  // 保存报告
  const reportPath = path.join(__dirname, '../docs/verification-report.json');
  fs.writeFileSync(reportPath, JSON.stringify(results, null, 2));
  log(colors.cyan, `\n📄 详细报告已保存到: ${reportPath}\n`);
  
  // 总结
  if (results.errors === 0 && results.warnings === 0) {
    log(colors.green, '🎉 恭喜！所有题目都通过了检查！');
  } else if (results.errors === 0) {
    log(colors.yellow, '⚠️  有一些警告，但没有严重错误。');
  } else {
    log(colors.red, `⚠️  发现 ${results.errors} 个错误需要修复。`);
  }
}

// 运行
main().catch(console.error);

